package client;

import java.util.List;
import java.util.Map;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

import cn.hutool.core.date.DateUtil;
import io.socket.client.IO;
import io.socket.client.Socket;
import io.socket.emitter.Emitter;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class SocketIOClientLaunch {

    public static void main(String[] args) {
        // 服务端socket.io连接通信地址
        String url = "http://127.0.0.1:8001";
        try {
            IO.Options options = new IO.Options();
            options.transports = new String[]{"websocket"};
            //options.reconnectionAttempts = 2;
            // 失败重连的时间间隔
            options.reconnectionDelay = 100000;
            // 连接超时时间(ms)
            options.timeout = 500000;
            Map<String, List<String>> headers = Maps.newHashMap();
            List<String> h = Lists.newArrayList();
            h.add("148777284263");
            headers.put("roomid", h);
            
            options.extraHeaders = headers;
            
            // userId: 唯一标识 传给服务端存储
            final Socket socket = IO.socket(url, options);
            
            socket.connect();
            
        	socket.on(Socket.EVENT_CONNECT, new Emitter.Listener() {
                @Override
                public void call(Object... args) {
                	log.info("client connect! ");
                    //socket.send("hello server, my name is client");
                }
            });
     
            socket.on(Socket.EVENT_DISCONNECT, new Emitter.Listener() {
                @Override
                public void call(Object... args) {
                	log.info("client disconnect! ");
                }
            });
     
            socket.on("text", new Emitter.Listener() {
                @Override
                public void call(Object... args) {
                    for (Object obj : args) {
                    	log.info("receive server message="+obj);
                    }
                }
            });
            
            socket.on("send", new Emitter.Listener() {
                @Override
                public void call(Object... args) {
                    for (Object obj : args) {
                    	log.info("receive server message="+obj);
                    }
                }
            });
            
            socket.on("close", new Emitter.Listener() {
                @Override
                public void call(Object... args) {
                    for (Object obj : args) {
                    	log.info("receive server message="+obj);
                    }
                }
            });
 
           

            //while (true) {
               
                // 自定义事件`push_data_event` -> 向服务端发送消息
            //socket.emit("text", "592961848898");
            //}
            Thread.currentThread().join();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
 